package com.live.crawler.util;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;

import static com.google.common.collect.Sets.newCopyOnWriteArraySet;
import static com.google.common.collect.Sets.newHashSet;

/**
 * 唯一消息队列
 * @author chengjian 
 * @date 2022/6/18
 */
public class UniqueQueue<T> extends ArrayBlockingQueue<T> {
    /** 弹幕队列最大存储弹幕量 上限阈值 **/
    private static final Integer BARRAGE_MAX_SIZE = 1000;

    /** 弹幕队列正常弹幕量 **/
    private static final Integer BARRAGE_NORMAL_SIZE = 500;

    private Set<T> set = newCopyOnWriteArraySet();

    private static final long serialVersionUID = 3339707581882532469L;

    public UniqueQueue(int capacity) {
        super(capacity);
    }

    @Override
    public boolean add(T e) {
        if (set.add(e)) {
            if (set.size() > BARRAGE_MAX_SIZE) {
                int total = 0;
                Set<T> newSet = newHashSet();
                Iterator<T> iterator = set.iterator();
                while (iterator.hasNext() && total++ < BARRAGE_NORMAL_SIZE) {
                    newSet.add(iterator.next());
                }
                set = newSet;
            }
            return super.add(e);
        }
        return true;
    }

    @Override
    public boolean remove(Object o) {
        set.remove(o);
        return super.remove(o);
    }
}
